package com.example.pclimb.ui.requests;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.pclimb.R;
import com.example.pclimb.model.ClimbRequest;
import com.example.pclimb.ui.adapters.ClimbRequestAdapter;
import com.example.pclimb.ui.payment.PaymentActivity;
import com.example.pclimb.viewmodel.ClimbRequestViewModel;

import java.util.ArrayList;

public class MatchedRequestsFragment extends Fragment {
    
    private static final String TAG = "MatchedRequestsFragment";
    private SwipeRefreshLayout swipeRefresh;
    private RecyclerView recyclerRequests;
    private TextView textEmpty;
    private ClimbRequestViewModel viewModel;
    private ClimbRequestAdapter adapter;
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_matched_requests, container, false);
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // 初始化视图
        swipeRefresh = view.findViewById(R.id.swipe_refresh);
        recyclerRequests = view.findViewById(R.id.recycler_requests);
        textEmpty = view.findViewById(R.id.text_empty);
        
        // 初始化ViewModel
        viewModel = new ViewModelProvider(requireActivity()).get(ClimbRequestViewModel.class);
        
        // 初始化适配器
        adapter = new ClimbRequestAdapter();
        
        // 设置RecyclerView
        recyclerRequests.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerRequests.setAdapter(adapter);
        
        // 设置列表项点击事件
        adapter.setOnItemClickListener(request -> {
            try {
                Log.d(TAG, "点击申请列表项，ID: " + request.getId());
                navigateToRequestDetail(request);
            } catch (Exception e) {
                Log.e(TAG, "处理申请列表项点击事件出错: ", e);
            }
        });
        
        // 设置操作按钮点击事件
        adapter.setOnActionClickListener(request -> {
            try {
                Log.d(TAG, "点击申请操作按钮，ID: " + request.getId());
                if (request.getStatus() == ClimbRequest.STATUS_MATCHED) {
                    // 已匹配状态，跳转到详情页
                    navigateToRequestDetail(request);
                }
            } catch (Exception e) {
                Log.e(TAG, "处理申请操作按钮点击事件出错: ", e);
            }
        });
        
        // 设置下拉刷新
        swipeRefresh.setOnRefreshListener(this::loadData);
        
        // 加载数据
        loadData();
    }

    /**
     * 跳转到请求详情页面
     */
    private void navigateToRequestDetail(ClimbRequest request) {
        Intent intent = new Intent(requireActivity(), RequestDetailActivity.class);
        intent.putExtra("request_id", (long)request.getId()); // 确保传递的是正确类型的ID
        startActivity(intent);
    }

    @Override
    public void onResume() {
        super.onResume();
        // 页面恢复时重新加载数据
        loadData();
    }
    
    private void loadData() {
        try {
            Log.d(TAG, "开始加载已匹配申请数据");
            // 从ViewModel加载已匹配申请数据
            viewModel.refreshMatchedRequests(); // 先刷新数据
            viewModel.getMatchedRequests().observe(getViewLifecycleOwner(), requests -> {
                // 数据加载完成，结束刷新动画
                if (swipeRefresh.isRefreshing()) {
                    swipeRefresh.setRefreshing(false);
                }
                
                Log.d(TAG, "观察到已匹配申请数据，数量: " + (requests != null ? requests.size() : 0));
                
                // 更新UI
                if (requests != null && !requests.isEmpty()) {
                    adapter.setRequests(requests);
                    textEmpty.setVisibility(View.GONE);
                    recyclerRequests.setVisibility(View.VISIBLE);
                } else {
                    adapter.setRequests(new ArrayList<>());
                    textEmpty.setVisibility(View.VISIBLE);
                    recyclerRequests.setVisibility(View.GONE);
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "加载已匹配申请数据出错: ", e);
            if (swipeRefresh.isRefreshing()) {
                swipeRefresh.setRefreshing(false);
            }
        }
    }
} 